package cn.rocksolid.sport.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class IOUtils {

  private static final int BUFSIZE_4K = 4096;
  private static final int EOS = -1;

  private IOUtils() {
  }

  public static String reading(InputStream is, int length) throws IOException {
    return reading(is, length, StandardCharsets.UTF_8);
  }

  public static String reading(InputStream is, int length, Charset charset) throws IOException {
    return new String(buffering(is, length), charset);
  }

  public static byte[] buffering(InputStream is, int length) throws IOException {
    return buffering(is, length, BUFSIZE_4K);
  }

  public static byte[] buffering(InputStream is, int length, int bufSize) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream(length);

    byte[] buf = new byte[bufSize];
    int counter = 0;
    int clipSize = 0;
    int limit = (length - counter) < bufSize ? length - counter : bufSize;
    while (0 < limit && (clipSize = is.read(buf, 0, limit)) > EOS) {
      baos.write(buf, 0, clipSize);
      counter += clipSize;
      limit = (length - counter) < bufSize ? length - counter : bufSize;
    }

    return baos.toByteArray();
  }

  public static byte[] buffering(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFSIZE_4K);
    byte[] buf = new byte[BUFSIZE_4K];
    int clipSize = 0;
    while ((clipSize = is.read(buf, 0, buf.length)) > EOS) {
      baos.write(buf, 0, clipSize);
    }
    return baos.toByteArray();
  }
}
